<template>
  <div class="card">
    <div class="title">{{ title }}</div>
    <div v-if="poolList.length">
      <div class="pool-wrapper">
        <div v-for="(pool, index) in poolList" :key="index" class="pool-item">
          <div @click.stop="toDetail(pool)">
            <!-- 标题 -->
            <div class="pool-wrapper_title">
              <div class="title_left">
                <img :src="require('@/assets/images/' + pool.imgName + '.png')" alt="pool-icon" />
                <div>
                  <div class="name">{{ pool.name }}</div>
                  <div class="tag-list" v-if="pool.label && pool.label.length">
                    <div class="tag" v-for="(tag, index) in pool.label" :key="index">{{ tag }}</div>
                  </div>
                </div>
              </div>
              <SubscribeComponent :pool="pool" @setSubGpcId="setSubGpcId(pool.id)" />
            </div>
            <!-- 简介、偏好 -->
            <div class="pool-wrapper_content">
              <div>简介：{{ pool.profile }}</div>
              <div>偏好：{{ pool.input }}</div>
            </div>
            <!-- 消息提醒 -->
            <div class="pool-wrapper_remind" v-if="pool.msg">
              <div
                class="point"
                :style="{
                  color: stockStatusColor[pool.msg.trace_type].color,
                  border: `1px solid ${stockStatusColor[pool.msg.trace_type].borderColor}`,
                  background: stockStatusColor[pool.msg.trace_type].bgColor,
                }"
              >
                {{
                  (stockStatusColor[pool.msg.trace_type] &&
                    stockStatusColor[pool.msg.trace_type].name) ||
                  '--'
                }}
              </div>
              <div class="text">
                {{ pool.msg.short_msg }}
              </div>
              <svg-icon icon="arrow-right"></svg-icon>
            </div>
          </div>
        </div>
      </div>
      <SubscribePopup
        :isShow="showSub"
        :gpcId="subGpcId"
        @updateIsShow="showSub = $event"
        @updateSubscribe="updateSubscribe"
      />
    </div>
    <div v-else>
      <NoData />
    </div>
  </div>
</template>

<script>
import { cfxfJudgeAuth, reqPoolSub } from '@/apis/pool.api';
import { POOL_LIST, BASE_URL, STAT, STOCK_STATES } from '@/config/pool';
import NoData from '@/components/common/NoData.vue';
import SubscribeComponent from '@/components/home/Subscribe.vue';
import SubscribePopup from '@/components/common/SubScribePopup.vue';

import { localStorageKey, localStorageFeatureHomeTips } from '@/config/pool.js';
import tools from '@/lib/tools.js';

const homeTipsTimeStorage = new tools.LocalStorageManager(
  localStorageKey,
  localStorageFeatureHomeTips
);

export default {
  components: {
    NoData,
    SubscribeComponent,
    SubscribePopup,
  },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 是否显示提醒
      showRemind: false,
      // 股池列表
      poolList: [],
      stockStatusColor: STOCK_STATES,
      showSub: false,
      subGpcId: 0,
    };
  },
  async mounted() {
    const product = window.getParam('product');
    if (product === 'cfxf') {
      const isRenew = await this.getCfxfRenewStatus();
      const len = Object.values(POOL_LIST[product]).length - 1;
      // cfxf最后一个股池为续费专享
      this.poolList = isRenew
        ? Object.values(POOL_LIST[product])
        : Object.values(POOL_LIST[product]).slice(0, len);
    } else {
      this.poolList = Object.values(POOL_LIST[product]);
    }
    this.getPoolSubStatus();
    // 监听跳转回时间
    this.$addEventListener('onShow', () => {
      this.getPoolSubStatus();
    });
  },
  methods: {
    async getPoolSubStatus() {
      try {
        const res = await reqPoolSub();
        if (res.status_code) {
          throw new Error(`JrdsHome.vue组件的getPoolSubStatus接口status_code异常:${res.status_code}`);
        }
        Object.keys(this.poolList).forEach(key => {
          this.poolList[key].isSubscribed = false;
        });
        for (const item of res.data) {
          const idx = this.poolList.findIndex(pool => pool.id === item.gpc_id);
          if (idx === -1) {
            continue;
          }
          this.poolList[idx].isSubscribed = true;
          const nowGpcTime = homeTipsTimeStorage.getItem(item.gpc_id)?.date;
          if(!item.latest_msg){
            continue;
          }
          const {
            latest_msg: { basic_date, trace_type, short_msg, stock_code, add_date },
          } = item;
          if (new Date(basic_date) > new Date(nowGpcTime) || !nowGpcTime) {
            this.$set(this.poolList[idx], 'msg', {
              basic_date,
              trace_type,
              short_msg,
              stock_code,
              add_date,
            });
          } else {
            // 不符合条件应当清空，防止返回页面onshow触发状态未改变
            this.$set(this.poolList[idx], 'msg', null);
          }
        }
      } catch (err) {
        _t.errorReport({...err});
      }
    },

    /**
     * 获取财富先锋是否续费
     */
    async getCfxfRenewStatus() {
      try {
        const res = await cfxfJudgeAuth();
        if (!res) {
          return false;
        }
        const resultArr = res.result || [];
        // cfxf续费标识
        const renewFlag = 34;
        return resultArr.includes(renewFlag);
      } catch (err) {
        const errInfo = {
          name: '接口请求异常',
          message: `msg:${err?.message || 'network error'},url:${err?.config?.url || 'cfxfJudgeAuth'}`,
          stack: '--'
        };
        _t.errorReport(errInfo);
        return false;
      }
    },

    /**
     * 跳转股池详情页
     */
    toDetail(pool) {
      let subMsgParam = '';
      if (pool.msg) {
        homeTipsTimeStorage.setItem(pool.id, { date: pool.msg.basic_date, showed: false });
        // 只取到日期
        const dateEndNum = 10;
        subMsgParam = `&addData=${pool.msg.add_date.slice(0, dateEndNum)}&stockCode=${pool.msg.stock_code}`;
      }
      window.hxmClickStat(`${STAT.PAGE_ID}.${pool.statId}`, { url_ver: STAT.URL_VER });
      // 都跳转跟踪池
      location.href = `${BASE_URL}details?gpc_id=${
        pool.id
      }&product=${window.getParam('product')}${subMsgParam}&isSub=${+pool.isSubscribed}`;
    },
    // 设置当前订阅弹框的股池id
    setSubGpcId(gpcId) {
      this.showSub = true;
      this.subGpcId = gpcId;
    },
    // 设置是否已订阅
    updateSubscribe(isSub) {
      this.poolList.forEach(pool => {
        if (pool.id === this.subGpcId) {
          pool.isSubscribed = isSub;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.title {
  font-size: 14px;
  font-weight: 700;
  color: var(--text-1);
  padding: 12px;
  border-bottom: 1px solid var(--text-4);
}

.pool-item {
  margin: 8px 6px;
  padding: 16px 10px;
  border-radius: 6px;
  background: var(--bg-color-2);
}

.tag-list {
  display: flex;
  margin-top: 6px;
  .tag {
    border: 0.33px solid var(--text-2);
    border-radius: 2px;
    font-size: 10px;
    color: var(--text-2);
    height: 14px;
    line-height: 14px;
    padding: 0 2px;
    margin-left: 8px;
  }
}

.pool-wrapper_remind {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 9px 8px;
  border-radius: 4px;
  background: var(--bg-color-1);
  font-size: 12px;
  color: var(--text-1);
  line-height: 16px;
  .point {
    padding: 0 2px;
    border-radius: 2px;
    line-height: 16px;
  }
  .text {
    margin-left: 6px;
    margin-right: 8px;
    width: 278px;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    white-space: nowrap;
  }
}

.pool-wrapper {
  position: relative;
  width: 7.42rem;
  font-size: 0.28rem;
  padding: 1px 0;
  .pool-wrapper_title {
    padding-bottom: 16px;
    display: flex;
    justify-content: space-between;
  }
  .title_left {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .name {
      white-space: nowrap;
      margin-left: 0.2rem;
      color: var(--text-1);
    }
    img {
      width: 0.8rem;
      height: 0.8rem;
    }
  }
  .pool-wrapper_title span img {
    pointer-events: none;
    width: 0.32rem;
    height: 0.25rem;
  }
  .pool-wrapper_content {
    font-size: 14px;
    line-height: 18px;
    color: var(--text-2);
    div:nth-child(2) {
      margin-top: 8px;
    }
  }
}
</style>
